package com.bluefish.bltuan.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import com.bluefish.bltuan.dao.CategoryDao;
import com.bluefish.bltuan.module.Category;
import com.bluefish.bltuan.util.PageIndex;

@Repository
public class CategoryDaoImpl extends AbstractDaoImpl<Category, Integer> implements CategoryDao {

	private static final String CITY_NAME = "name";

	private static final long serialVersionUID = 8933619290204206637L;

	private static final String TYPE = "type";
	
	private static final String LIST_BY_TYPE = "from Category c where c.parent.type=:type";
	
	private static final String COUNT_LIST_BY_TYPE = "select count(*) from Category c where c.parent.type=:type";

	private static final String CITY_NICK_NAME = "nickname";
	
	public List<Category> getCategoryByType(int type) {
		return getParentByType(type).getChildren();
	}

	public Category getParentByType(int type) {
		return getByProperty(TYPE, type);
	}
	
	public List<Category> getStartedCategoryByType(int type) {
		List<Category> categories = new ArrayList<Category>();
		Category category = getParentByType(type);
		if(category != null){
			for(Category c:category.getChildren()){
				if(c.isStart())
					categories.add(c);
			}
		}
		return categories;
	}

	@SuppressWarnings("unchecked")
	public List<Category> list(final PageIndex pageIndex, final int type) {
		return this.getHibernateTemplate().executeFind(new HibernateCallback<List<Category>>() {

			public List<Category> doInHibernate(Session session) throws HibernateException,
					SQLException {
				Query countQuery = session.createQuery(COUNT_LIST_BY_TYPE)
					.setParameter(TYPE, type);
				int count = ((Number)countQuery.uniqueResult()).intValue();
				pageIndex.setTotalRows(count);
				Query query = session.createQuery(LIST_BY_TYPE).setParameter(TYPE, type);
				query.setFirstResult(pageIndex.getStartRow());
				query.setMaxResults(pageIndex.getPageSize());
				return query.list();
			}
		});
	}

	public List<Category> listByCityName(String cityName) {
		return listByProperty(CITY_NAME, cityName);
	}
	
	public List<Category> listByCityNickName(String nickname) {
		return listByProperty(CITY_NICK_NAME, nickname);
	}
}
